<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>圆的直线运动</title>
</head>
<body style="margin: 0;padding: 0;" onload="draw()">
<canvas id="canvas" width="800px" height="400px" style="border: solid 1px #000;"></canvas>
<script>
function draw(){
  let canvas = document.querySelector("#canvas");
  if(canvas.getContext){
    //创建context对象
    let cvsCtx = canvas.getContext("2d");
    //1.绘制图像
    //2.清除画布
    //3.更新位置
    //4.绘制图像 2. 3. 4.
    //面向对象
    function Cir(x,y,r,color,speedX,speedY){
      this.x = x;
      this.y = y;
      this.r = r
      this.color = color;
      this.speedX = speedX;
      this.speedY = speedY;
    }
    Cir.prototype.draw = function(){
      cvsCtx.beginPath();
      cvsCtx.fillStyle = this.color;
      cvsCtx.arc(this.x, this.y, this.r, 0,2*Math.PI);
      cvsCtx.fill();
    } 
    Cir.prototype.move = function(){
      
      //更新位置
      this.x += this.speedX;
      if(this.x > canvas.width-this.r || this.x < this.r){
        this.speedX *= -1;
      }
      this.y += this.speedY;
      if(this.y > canvas.height-this.r || this.y < this.r){
        this.speedY *= -1;
      }

    }
    function init(){
      //清除画布
      cvsCtx.clearRect(0, 0, canvas.width, canvas.height);
      cir.draw();
      cir.move();
      cir2.draw();
      cir2.move();
      //请求关键帧动画
      requestAnimationFrame(init);
    }  
    let cir = new Cir(50,50,50,'pink',5,5);
    let cir2 = new Cir(350,250,50,'skyblue',5,5);
    init();
  }
}
</script>
</body>
</html>